﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Nop.Admin.Models.WindAlert;
using Nop.Admin.WindAlert;
using Nop.Core;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.WindAlert;
using Nop.Services.ExportImport;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Security;
using Nop.Services.Seo;
using Nop.Services.WindAlert;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;


namespace Nop.Admin.Controllers
{
    public partial class WCameraController : BaseAdminController
    {
        #region Fields
        private readonly ILanguageService _languageService;
        private readonly ILocalizationService _localizationService;
        private readonly ILocalizedEntityService _localizedEntityService;
        private readonly ICustomerActivityService _customerActivityService;
        private readonly IExportManager _exportManager;
        private readonly IWorkContext _workContext;
        private readonly IPermissionService _permissionService;
        private readonly AdminAreaSettings _adminAreaSettings;
        private readonly IUrlRecordService _urlRecordService;
        private readonly ICameraService _cameraService;
        #endregion

        #region Constructors
        
        public WCameraController(ILanguageService languageService,
            ILocalizationService localizationService, ILocalizedEntityService localizedEntityService,
            ICustomerActivityService customerActivityService, 
            IExportManager exportManager, IWorkContext workContext,
            IPermissionService permissionService,
            AdminAreaSettings adminAreaSettings, IUrlRecordService urlRecordService,
            ICameraService CameraService)
        {
            this._languageService = languageService;
            this._localizationService = localizationService;
            this._localizedEntityService = localizedEntityService;
            this._customerActivityService = customerActivityService;
            this._exportManager = exportManager;
            this._workContext = workContext;
            this._permissionService = permissionService;
            this._adminAreaSettings = adminAreaSettings;
            this._urlRecordService = urlRecordService;
            this._cameraService = CameraService;
        }

        #endregion

        #region Utilities

        [NonAction]
        public void UpdateLocales(Camera camera, CameraModel model)
        {
            foreach (var localized in model.Locales)
            {
                _localizedEntityService.SaveLocalizedValue(camera,
                                                               x => x.Name,
                                                               localized.Name,
                                                               localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(camera,
                                                           x => x.Description,
                                                           localized.Description,
                                                           localized.LanguageId);
                
                _localizedEntityService.SaveLocalizedValue(camera,
                                                           x => x.SponserName,
                                                           localized.SponserName,
                                                           localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(camera,
                                                           x => x.MetaKeywords,
                                                           localized.MetaKeywords,
                                                           localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(camera,
                                                           x => x.MetaDescription,
                                                           localized.MetaDescription,
                                                           localized.LanguageId);

                _localizedEntityService.SaveLocalizedValue(camera,
                                                           x => x.MetaTitle,
                                                           localized.MetaTitle,
                                                           localized.LanguageId);

                //search engine name
                var seName = camera.ValidateSeName(localized.SeName, localized.Name, false);
                _urlRecordService.SaveSlug(camera, seName, localized.LanguageId);
            }
        }
        #endregion

        #region Methods
        #region Create / Edit / Delete / List
        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            return View();
        }

        [HttpPost]
        public ActionResult List(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();
            var cameras = _cameraService.GetAllCameras(command.Page - 1, command.PageSize, true);
            var gridModel = new DataSourceResult
            {
                Data = cameras.Select(x => x.ToModel()),
                Total = cameras.TotalCount
            };
            return new JsonResult
            {
                Data = gridModel
            };
        }

        public ActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var model = new CameraModel();
            //locales
            AddLocales(_languageService, model.Locales);
            //default values
            model.Published = true;
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Create(CameraModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //decode description
            model.Description = HttpUtility.HtmlDecode(model.Description);
            foreach (var localized in model.Locales)
                localized.Description = HttpUtility.HtmlDecode(localized.Description);

            if (ModelState.IsValid)
            {
                var camera= model.ToEntity();
                camera.CreatedOnUtc = DateTime.UtcNow;
                camera.UpdatedOnUtc = DateTime.UtcNow;
                _cameraService.InsertCamera(camera);
                //search engine name
                model.SeName = camera.ValidateSeName(model.SeName, camera.Name, true);
                _urlRecordService.SaveSlug(camera, model.SeName, 0);
                //locales
                UpdateLocales(camera, model);

                //activity log
                _customerActivityService.InsertActivity("AddNewCamera", _localizationService.GetResource("ActivityLog.AddNewCamera"), camera.Name);

                SuccessNotification(_localizationService.GetResource("Admin.WindAlert.Cameras.Added"));
                return continueEditing ? RedirectToAction("Edit", new { id = camera.Id }) : RedirectToAction("List");
            }

            return View(model);
        }

        public ActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var camera = _cameraService.GetCameraById(id);
            if (camera == null || camera.Deleted)
                //No camera found with the specified id
                return RedirectToAction("List");

            var model = camera.ToModel();
            //locales
            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.Name = camera.GetLocalized(x => x.Name, languageId, false, false);
                locale.Description = camera.GetLocalized(x => x.Description, languageId, false, false);
                locale.SponserName = camera.GetLocalized(x => x.SponserName, languageId, false, false);
                locale.MetaKeywords = camera.GetLocalized(x => x.MetaKeywords, languageId, false, false);
                locale.MetaDescription = camera.GetLocalized(x => x.MetaDescription, languageId, false, false);
                locale.MetaTitle = camera.GetLocalized(x => x.MetaTitle, languageId, false, false);
                locale.SeName = camera.GetSeName(languageId, false, false);
            });
 
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Edit(CameraModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var camera = _cameraService.GetCameraById(model.Id);
            if (camera == null || camera.Deleted)
                //No camera found with the specified id	
                return RedirectToAction("List");

            //decode description
            model.Description = HttpUtility.HtmlDecode(model.Description);
            foreach (var localized in model.Locales)
                localized.Description = HttpUtility.HtmlDecode(localized.Description);


            if (ModelState.IsValid)
            {
                camera = model.ToEntity(camera);
                camera.UpdatedOnUtc = DateTime.UtcNow;
                _cameraService.UpdateCamera(camera);
                //search engine name
                model.SeName = camera.ValidateSeName(model.SeName, camera.Name, true);
                _urlRecordService.SaveSlug(camera, model.SeName, 0);
                //locales
                UpdateLocales(camera, model);

                //activity log
                _customerActivityService.InsertActivity("EditCamera", _localizationService.GetResource("ActivityLog.EditCamera"), camera.Name);

                SuccessNotification(_localizationService.GetResource("Admin.WindAlert.Cameras.Updated"));
                if (continueEditing)
	            {
	                 //selected tab
	                 SaveSelectedTabIndex();
	 
	                 return RedirectToAction("Edit", new {id = camera.Id});
	            }
	            else
	            {
	                return RedirectToAction("List");
	            }
            }
            return View(model);
        }

        [HttpPost]
       public ActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var camera = _cameraService.GetCameraById(id);
            if (camera == null)
                //No camera found with the specified id	
                return RedirectToAction("List");
            _cameraService.DeleteCamera(camera);

            //activity log
            _customerActivityService.InsertActivity("DeleteCamera", _localizationService.GetResource("ActivityLog.DeleteCamera"), camera.Name);

            SuccessNotification(_localizationService.GetResource("Admin.WindAlert.Cameras.Deleted"));
            return RedirectToAction("List");
        }
        #endregion

        
        #endregion

    }
}
